package com.github.binarywang.demo.wx.mp.service;

import com.alibaba.fastjson.JSON;
import com.github.binarywang.demo.wx.mp.beans.FocusParam;
import com.github.binarywang.demo.wx.mp.service.oss.AliOssService;
import com.github.binarywang.demo.wx.mp.utils.QRCodeUtils;
import com.github.binarywang.demo.wx.mp.wxService.MulitConfigService;
import com.github.binarywang.demo.wx.mp.wxService.WxMulitService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xiaoban
 * @date 2021/9/3 上午12:07
 */
@Service
@Slf4j
public class QrService {

//    @Autowired
//    private WxMpService wxMpService;

    @Autowired
    MulitConfigService mulitConfigService;

    @Autowired
    private RedisService redisService;


    @Autowired
    private AliOssService aliOssService;

    public byte[] getUrl(String openId,Long merchantsId ) {
        try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
            //            String sceneStr = "MC="+merchantsId+",appId="+appId+",LS_FOCUS";
            generate(openId, merchantsId, os);
            return os.toByteArray();

        } catch (Exception e) {
            log.error("获取二维码失败!", e);
        }
        return null;
    }

    private String generate(String client_id, Long merchantsId, FastByteArrayOutputStream os) throws Exception {
//        WxMpService wxMpService = this.wxMpService.switchoverTo(appId);修改
        WxMulitService wxService = mulitConfigService.getWxMulitService(client_id);
        FocusParam param = FocusParam
            .builder()
            .client_id(client_id)
//            .appId(appId)
            .mc(""+merchantsId)
            .t("LS_FOCUS")
            .build();
        String key = param.getT() + ":"+param.getMc() +":"+param.getClient_id();//getAppId
        String sceneStr = JSON.toJSONString(param);
        String url=redisService.getObj(key);
        if (StringUtils.isBlank(url)){
            WxMpQrcodeService qrcodeService = wxService.getQrcodeService();
            WxMpQrCodeTicket wxMpQrCodeTicket;
            wxMpQrCodeTicket = qrcodeService.qrCodeCreateLastTicket(sceneStr);

            url = wxMpQrCodeTicket.getUrl();
        }else{
            System.out.println("缓存读取...");
        }
        if (StringUtils.isBlank(url)){
            log.error("生成二维码失败了");
            return null;
        }
        log.info("生成二维码 {} {}",key,url);
        redisService.set(key,url,3600*24);
        log.debug("生成二维码! -> {}",url);
        QRCodeUtils.encode(url,null, os);
//        return Result.success(url);
        return url;
    }


    public String getQrUrl(String client_id, Long merchantsId) {
        FocusParam param = FocusParam
            .builder()
            .client_id(client_id)
//            .appId(appId)
            .mc(""+merchantsId)
            .t("LS_FOCUS")
            .build();
        log.info("================>>>>>>>merchantsId:  "+merchantsId);

        String key = "qrAli:"+param.getT()+":"+param.getMc()+":"+param.getClient_id()+"";
        String url = redisService.getObj(key);
        if (StringUtils.isNotBlank(url)){
            return url;
        }
        try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
            generate(client_id, merchantsId, os);
            String name = "yunfen/";
            SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
            name += "qr/" + client_id + sdf.format(new Date()) + client_id +".jpg";
            String link = aliOssService.upload(name, os.getInputStream(), (long) os.size());
            if (StringUtils.isNotBlank(link)) {
                log.info("上传阿里成功 {}," + link);
                redisService.set(key, link);
                return link;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("没有上传到阿里云");
        return null;
    }
}
